package com.zwh.spring.demo.exception;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zwh.spring.demo.domain.ErrorInfo;

@ControllerAdvice
public class GlobalExceptionHandler {

	public static final String DEFAULT_ERROR_VIEW = "error";
	
	@ExceptionHandler
	public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception{
		
		if(e instanceof IllegalArgumentException) {
			//...
		}
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e)
			.addObject("url",  req.getRequestURL())
			.setViewName(DEFAULT_ERROR_VIEW);
		
		return mav;
	}
	
	@ExceptionHandler(value= ApiException.class)
	@ResponseBody
	public ErrorInfo<String> defaultErrorHandler1(HttpServletRequest req, Exception e) throws Exception{
		
		ErrorInfo<String> r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Some Data");
        r.setUrl(req.getRequestURL().toString());
		
		return r;
	}
}
